package cn.com.gzheroli.auth.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.gzheroli.auth.pojo.TSDatacondition;
import cn.com.gzheroli.auth.pojo.TSDatarule;
import cn.com.gzheroli.auth.pojo.TSDataruleGroup;
import cn.com.gzheroli.auth.pojo.TSRoleDatarule;
import cn.com.gzheroli.auth.service.TSDataruleService;
import cn.com.gzheroli.bfw.pojo.base.TSUser;
import cn.com.gzheroli.cache.SpringRedisCache;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.manager.Client;
import cn.com.gzheroli.core.util.NameHandler;
import cn.com.gzheroli.core.util.RequestUtil;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.util.GenSqlUtil;



/**
 * 
* @类名: TSDataruleController  
* @描述: 数据规则  
* @作者: 李长荣 lichang_20011@163.com  
* @日期: 2017年7月8日  下午6:28:25
*@version V1.0  
*
 */
@Controller
@RequestMapping("/api/dataRuleController")
public class TSDataruleController  {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(TSDataruleController.class);

	@Autowired
	private TSDataruleService dataruleService;
	@Autowired
	private CommonService commonService;
	@Autowired
    private SpringRedisCache cache;
	@Autowired
	private SystemService systemService;


	/**
	 * 
	* @Title: getDataRuleList 
	* @Description: 获取规则列表
	* @param @param request
	* @param @param response
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataRuleList")
	@ResponseBody
	public AjaxJson getDataRuleList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j =  new AjaxJson();
		boolean success=true;
		String msg="获取成功";
		
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"10":request.getParameter("rows");
		Integer start = Integer.valueOf((Integer.parseInt(page) - 1) * Integer.parseInt(rows));
		Integer end = Integer.valueOf(Integer.parseInt(page) * Integer.parseInt(rows));
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		Map reqMap=RequestUtil.convertParameterToMap(request);
	    //HashMap para=new HashMap();
	    Map conMap=new HashMap();
	    reqMap.put("status", "1");
	    conMap.put("status", "=");
	    String tableName = new NameHandler().getTableName(TSDatarule.class.getSimpleName());
	    Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,TSDatarule.class);
		String sql=GenSqlUtil.genSqlByClass(TSDatarule.class, conMap,"list",tableColumns,"d");
		List beanList =commonService.findForJdbcPage(sql, TSDatarule.class, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		String countSql=GenSqlUtil.genSqlByClass(TSDatarule.class, conMap,"count",tableColumns,"d");
		Long total=commonService.getCountForJdbc(countSql, reqMap);
		j.setTotal(total);
		j.setObj(beanList);
		j.setMsg(msg);
		j.setSuccess(success);
		return j;
	}
	/**
	 * 
	* @Title: getDataruleGroupList 
	* @Description: 获取规则分组列表
	* @param @param request
	* @param @param response
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataruleGroupList")
	@ResponseBody
	public AjaxJson getDataruleGroupList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j =  new AjaxJson();
		boolean success=true;
		String msg="获取成功";
		
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"10":request.getParameter("rows");
		String ruleId=request.getParameter("ruleId")==null?"":request.getParameter("ruleId");
		Integer start = Integer.valueOf((Integer.parseInt(page) - 1) * Integer.parseInt(rows));
		Integer end = Integer.valueOf(Integer.parseInt(page) * Integer.parseInt(rows));
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
	    HashMap para=new HashMap();
	    para.put("ruleId", ruleId);
	    
	    //String sql="select * from T_S_DATARULE_GROUP where 1=1";
	    //sql=sql+" and  RULE_ID=#{ruleId}";
	    Map reqMap=RequestUtil.convertParameterToMap(request);
	    Map conMap=new HashMap();
	    if(reqMap.containsKey("ruleId"))
			conMap.put("ruleId", "=");
	    reqMap.put("status", "1");
	    conMap.put("status", "=");
	    String tableName = new NameHandler().getTableName(TSDataruleGroup.class.getSimpleName());
	    Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,TSDataruleGroup.class);
		String sql=GenSqlUtil.genSqlByClass(TSDataruleGroup.class, conMap,"list",tableColumns,"dg");
		List beanList =commonService.findForJdbcPage(sql, TSDataruleGroup.class, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		String countSql=GenSqlUtil.genSqlByClass(TSDataruleGroup.class, conMap,"count",tableColumns,"dg");
		Long total=commonService.getCountForJdbc(countSql, reqMap);
		j.setTotal(total);
		j.setObj(beanList);
		j.setMsg(msg);
		j.setSuccess(success);
		return j;
	}
	/**
	 * 
	* @Title: getDataconditionList 
	* @Description: 获取规则条件列表
	* @param @param request
	* @param @param response
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataconditionList")
	@ResponseBody
	public AjaxJson getDataconditionList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j =  new AjaxJson();
		boolean success=true;
		String msg="获取成功";
		
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"10":request.getParameter("rows");
		String ruleId=request.getParameter("ruleId")==null?"":request.getParameter("ruleId");
		String groupId=request.getParameter("groupId")==null?"":request.getParameter("groupId");
		Integer start = Integer.valueOf((Integer.parseInt(page) - 1) * Integer.parseInt(rows));
		Integer end = Integer.valueOf(Integer.parseInt(page) * Integer.parseInt(rows));
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
	    HashMap para=new HashMap();
	    //para.put("ruleId", ruleId);
	    para.put("groupId", groupId);
	    //String sql="select * from T_S_DATACONDITION where 1=1 ";
	    //sql=sql+" and  GROUP_ID=#{groupId}";
	    Map reqMap=RequestUtil.convertParameterToMap(request);
	    Map conMap=new HashMap();
	    if(reqMap.containsKey("groupId"))
			conMap.put("groupId", "=");
	    reqMap.put("status", "1");
	    conMap.put("status", "=");
	    String tableName = new NameHandler().getTableName(TSDatacondition.class.getSimpleName());
	    Map<String,Object> tableColumns=systemService.getHeroTableColumns(tableName,TSDatacondition.class);
		String sql=GenSqlUtil.genSqlByClass(TSDatacondition.class, conMap,"list",tableColumns,"dc");
		List beanList =commonService.findForJdbcPage(sql, TSDatacondition.class, reqMap, Integer.parseInt(page), Integer.parseInt(rows));
		String countSql=GenSqlUtil.genSqlByClass(TSDatacondition.class, conMap,"count",tableColumns,"dc");
		Long total=commonService.getCountForJdbc(countSql, reqMap);
		j.setTotal(total);
		j.setObj(beanList);
		j.setMsg(msg);
		j.setSuccess(success);
		return j;
	}

	/**
	 * 
	* @Title: delDatarule 
	* @Description: 删除规则
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "delDatarule")
	@ResponseBody
	public AjaxJson delDatarule(String ids, HttpServletRequest request) {
		String message = "规则删除成功";
		AjaxJson j = new AjaxJson();
		String[] idArr=ids.split(",");
		for(String id:idArr){
			if(id!=null&&!id.trim().equals("")){
//				TSDatarule tSDatarule = commonService.get(TSDatarule.class, id);
//				tSDatarule.setStatus("0");
//				commonService.update(tSDatarule);
				Map whereMap=new HashMap();
				whereMap.put("id", id);
				Map paraMap=new HashMap();
				paraMap.put("status", "0");
				commonService.updateField(paraMap, whereMap, TSDatarule.class);
				
				//commonService.delete(TSDatarule.class, id);
				j.setSuccess(true);
			}else{
				j.setSuccess(false);
				message = "id为空";
			}
		}
//		TSDatarule tSDatarule = commonService.get(TSDatarule.class, id);
//		
//		try{
//			tSDatarule.setStatus("0");
//			commonService.update(tSDatarule);
//		}catch(Exception e){
//			e.printStackTrace();
//			message = "规则删除失败";
//		}
		j.setMsg(message);
		return j;
	}
	


	
	/**
	 * 
	* @Title: saveDatarule 
	* @Description: 保存规则数据
	* @param @param tSDatarule
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "saveDatarule")
	@ResponseBody
	public AjaxJson saveDatarule(TSDatarule tSDatarule, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "保存成功";
		try {
			if(tSDatarule.getId()!=null&&!tSDatarule.getId().trim().equals("")){
				commonService.update(tSDatarule);
			}else{
				commonService.save(tSDatarule);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "保存失败";
		}
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 
	* @Title: getDataruleData 
	* @Description: 获取规则数据 
	* @param @param tSDatarule
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataruleData")
	@ResponseBody
	public AjaxJson getDataruleData(TSDatarule tSDatarule, HttpServletRequest request) {
		AjaxJson j =  new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		String moduleName=tSDatarule.getModuleName();
		TSUser user=client.getUser();
		if (StringUtil.isNotEmpty(tSDatarule.getId())) {
			tSDatarule = commonService.get(TSDatarule.class, tSDatarule.getId());
			moduleName=tSDatarule.getModuleName();
			j.setObj(tSDatarule);
		}
		//String tableName=request.getParameter("tableName")==null?"tt":request.getParameter("tableName");
		String sql=dataruleService.genSqlByModuleName(moduleName,"td",user);
		
		Map attributes=new HashMap();
		attributes.put("sql", sql);
		j.setAttributes(attributes);
		j.setMsg("获取成功!");
		j.setSuccess(true);
		return j;
	}
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 
	* @Title: delDataruleGroup 
	* @Description: 规则分组-删除 
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "delDataruleGroup")
	@ResponseBody
	public AjaxJson delDataruleGroup(String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		TSDataruleGroup group = commonService.get(TSDataruleGroup.class, id);
		String message = "规则分组删除成功";
		try{
			group.setStatus("0");
			commonService.update(group);
		}catch(Exception e){
			e.printStackTrace();
			message = "规则分组删除失败";
		}
		j.setMsg(message);
		return j;
	}
	


	
	/**
	 * 
	* @Title: saveDataruleGroup 
	* @Description: 规则分组-保存 
	* @param @param group
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "saveDataruleGroup")
	@ResponseBody
	public AjaxJson saveDataruleGroup(TSDataruleGroup group, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "保存成功";
		try {
			if(group.getId()!=null&&!group.getId().trim().equals("")){
				commonService.update(group);
			}else{
				commonService.save(group);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "保存失败";
		}
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 
	* @Title: getDataruleGroupData 
	* @Description: 规则分组-数据获取
	* @param @param group
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataruleGroupData")
	@ResponseBody
	public AjaxJson getDataruleGroupData(TSDataruleGroup group, HttpServletRequest request) {
		AjaxJson j =  new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		if (StringUtil.isNotEmpty(group.getId())) {
			group = commonService.get(TSDataruleGroup.class, group.getId());
			j.setObj(group);
		}
		List<TSDataruleGroup> datagrouprules=commonService.findByProperty(TSDataruleGroup.class, "ruleId", group.getRuleId());
		Map attributes=new HashMap();
		attributes.put("datagrouprules", datagrouprules);
		j.setAttributes(attributes);
		j.setMsg("获取成功!");
		j.setSuccess(true);
		return j;
	}
	@RequestMapping(value = "getGroupListData")
	@ResponseBody
	public AjaxJson getGroupListData(String ruleId, HttpServletRequest request) {
		AjaxJson j =  new AjaxJson();
		List<TSDataruleGroup> datagrouprules=commonService.findByProperty(TSDataruleGroup.class, "ruleId", ruleId);
		j.setObj(datagrouprules);
		j.setMsg("获取成功!");
		j.setSuccess(true);
		return j;
	}
	////////////////////////////////////////////////////////////////////////////////////////////////
	/**
	 * 
	* @Title: delDataruleCondition 
	* @Description: 数据规则条件-删除 
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "delDataruleCondition")
	@ResponseBody
	public AjaxJson delDataruleCondition(String id, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		TSDatacondition condition = commonService.get(TSDatacondition.class, id);
		String message = "数据规则条件删除成功";
		try{
			condition.setStatus("0");
			commonService.update(condition);
		}catch(Exception e){
			e.printStackTrace();
			message = "数据规则条件删除失败";
		}
		j.setMsg(message);
		return j;
	}
	


	
	/**
	 * 
	* @Title: saveDataruleCondition 
	* @Description: 数据规则条件 --保存 
	* @param @param condition
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "saveDataruleCondition")
	@ResponseBody
	public AjaxJson saveDataruleCondition(TSDatacondition condition, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "保存成功";
		try {
			if(condition.getId()!=null&&!condition.getId().trim().equals("")){
				commonService.update(condition);
			}else{
				commonService.save(condition);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "保存失败";
		}
		j.setSuccess(true);
		j.setMsg(message);
		return j;
	}
	

	/**
	 * 
	* @Title: getDataruleConditionData 
	* @Description: 数据规则条件--数据获取
	* @param @param condition
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getDataruleConditionData")
	@ResponseBody
	public AjaxJson getDataruleConditionData(TSDatacondition condition, HttpServletRequest request) {
		AjaxJson j =  new AjaxJson();
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		if (StringUtil.isNotEmpty(condition.getId())) {
			condition = commonService.get(TSDatacondition.class, condition.getId());
			j.setObj(condition);
		}
		j.setObj(condition);
		j.setMsg("获取成功!");
		j.setSuccess(true);
		return j;
	}
	/**
	 * 
	* @Title: getRoleRuleList 
	* @Description: 获取角色拥有的规则列表
	* @param @param request
	* @param @param response
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "getRoleRuleList")
	@ResponseBody
	public AjaxJson getRoleRuleList(HttpServletRequest request, HttpServletResponse response) {
		AjaxJson j =  new AjaxJson();
		boolean success=true;
		String msg="获取成功";
		
		String page=request.getParameter("page")==null?"1":request.getParameter("page");
		String rows=request.getParameter("rows")==null?"10":request.getParameter("rows");
		Integer start = Integer.valueOf((Integer.parseInt(page) - 1) * Integer.parseInt(rows));
		Integer end = Integer.valueOf(Integer.parseInt(page) * Integer.parseInt(rows));
		String token = request.getHeader("token")==null?request.getParameter("token"):request.getHeader("token");
		Client client=cache.getCache(token, Client.class);
		if(client==null||client.getUser()==null){
			j.setSuccess(false);
			j.setMsg("尚未登录,请登录!");
			return j;
		}
		TSUser user=client.getUser();
		Map reqMap=RequestUtil.convertParameterToMap(request);
	    //HashMap para=new HashMap();
	    Map conMap=new HashMap();
	    reqMap.put("status", "1");
	    if(reqMap.containsKey("roleId"))
	    	conMap.put("roleId", "=");
	    conMap.put("status", "=");
//	    String tableName = new DefaultNameHandler().getTableName(TSRoleDatarule.class.getSimpleName());
//		List<String> tableColumns=systemService.getTableColumns(tableName);
//		String sql=GenSqlUtil.genSqlByClass(TSRoleDatarule.class, conMap,"list",tableColumns);
	    j=dataruleService.getRoleRuleList(reqMap,page,rows);
		j.setMsg(msg);
		j.setSuccess(success);
		return j;
	}
	/**
	 * 
	* @Title: saveRoleDataRule 
	* @Description: 保存角色数据规则数据
	* @param @param group
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "saveRoleDataRule")
	@ResponseBody
	public AjaxJson saveRoleDataRule(String ids,String roleCode, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "保存成功";
		try {
			if(ids==null||ids.trim().equals("")||roleCode==null||roleCode.trim().equals("")){
				message = "保存失败";
				j.setSuccess(false);
			}else{
				String[] idArr=ids.split(",");
				for(String id:idArr){
					Map para=new HashMap();
					para.put("roleCode", roleCode);
					para.put("ruleCode", id);
					List<TSRoleDatarule> list=dataruleService.getRoleRuleList(para);
					if(list!=null&&!list.isEmpty())
						continue;
					else{
						TSRoleDatarule roleDataRule=new TSRoleDatarule();	
						roleDataRule.setRoleCode(roleCode);
						roleDataRule.setRuleCode(id);
						roleDataRule.setStatus("1");
						commonService.save(roleDataRule);
					}	
				}
				j.setSuccess(true);
			}
		} catch (Exception e) {
			e.printStackTrace();
			message = "保存失败";
		}
		
		j.setMsg(message);
		return j;
	}
	/**
	 * 
	* @Title: delRoleDataRule 
	* @Description: 删除角色数据规则
	* @param @param id
	* @param @param request
	* @param @return    设定文件 
	* @return AjaxJson    返回类型 
	* @throws
	 */
	@RequestMapping(value = "delRoleDataRule")
	@ResponseBody
	public AjaxJson delRoleDataRule(String ids, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String message = "删除成功";
		try {
			String[] idArr=ids.split(",");
			for(String id:idArr){
				if(id!=null&&!id.trim().equals("")){
					commonService.delete(TSRoleDatarule.class, id);
					j.setSuccess(true);
				}else{
					j.setSuccess(false);
					message = "id为空";
				}
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			message = "删除失败";
			j.setSuccess(false);
		}
		
		j.setMsg(message);
		return j;
	}
}
